﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Reflection;
using System.Diagnostics;

namespace wpf_print.utils
{
    internal class NoRepeatStart
    {
        private static Semaphore singleInstanceWatcher;
        private static bool createdNew;
        public static void Start() {
            singleInstanceWatcher = new Semaphore(
                    0,
                    1,
                Assembly.GetExecutingAssembly().GetName().Name,
                out createdNew);

            if (!createdNew)
            {
                Process current = Process.GetCurrentProcess();
                foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id)
                    {
                        NativeMethods.SetForegroundWindow(process.MainWindowHandle);
                        NativeMethods.ShowWindow(process.MainWindowHandle, WindowShowStyle.ShowMinimized);
                        NativeMethods.ShowWindow(process.MainWindowHandle, WindowShowStyle.ShowNormal);
                        break;
                    }
                }
                Environment.Exit(-2);
            }
        }
        
    }


    internal enum WindowShowStyle : uint
    {
        Hide = 0,
        ShowNormal = 1,
        ShowMinimized = 2,
        ShowMaximized = 3,
        Maximize = 3,
        ShowNormalNoActivate = 4,
        Show = 5,
        Minimize = 6,
        ShowMinNoActivate = 7,
        ShowNoActivate = 8,
        Restore = 9,
        ShowDefault = 10,
        ForceMinimized = 11
    }
    static class NativeMethods
    {
        [DllImport("user32.dll")]
        internal static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        internal static extern bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow);
    }
}
